package com.gxuwz.leave.servlet;

import com.gxuwz.leave.context.AppContext;
import com.gxuwz.leave.entity.Course;
import com.gxuwz.leave.entity.Department;
import com.gxuwz.leave.entity.Leave;
import com.gxuwz.leave.service.CourseService;
import com.gxuwz.leave.service.LeaveService;
import com.gxuwz.leave.service.LeaveServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import static com.gxuwz.leave.tools.SerialNumberGenerator.generateSerialNumber;

@WebServlet(name="leaveServlet", urlPatterns = {"/leave"})
public class LeaveServlet extends BaseHttpServlet{
    private final static String VIEW_ADD = "/WEB-INF/views/leave/leave_add.jsp";

    private final static String VIEW_EXPORT = "/WEB-INF/views/leave/inst_leave_export.jsp";
    private final static String STU_VIEW_LIST = "/WEB-INF/views/leave/stu_leave_list.jsp";

    private final static String INST_VIEW_LIST = "/WEB-INF/views/leave/inst_leave_list.jsp";
    private final static String STU_ACTION_LIST = "/leave?action=list";

    private final static String INST_ACTION_LIST = "/leave?action=listAll";
    private LeaveService leaveService;

    private CourseService courseService;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");

        String view = ErrorPage_500;
        try{
            switch (action){
                //导向新增页面
                case "input":
                    view = VIEW_ADD;
                    //获取生成的请假单号
                    String leaveID = generateSerialNumber();
                    req.setAttribute("leaveID", leaveID);
                    List<Course> courseList = courseService.list(null);
                    req.setAttribute("courseList", courseList);
                    break;
                //提交新增
                case "add":
                    // 当前时间
                    LocalDateTime now = LocalDateTime.now();
                    Leave leave = new Leave();
                    leave.setLeaveID(req.getParameter("leaveID"));
                    leave.setCourseID(req.getParameter("courseID"));
                    leave.setReason(req.getParameter("reason"));
                    String daynumStr = req.getParameter("daynum"); // 获取前端传递的字符串
                    int daynum = Integer.parseInt(daynumStr);         // 将字符串转换为整数
                    leave.setDaynum(daynum);                          // 设置到实体类中
                    leave.setStuNo((String) req.getSession().getAttribute("userID"));
                    //开始状态置0
                    leave.setStatus("0");
                    //转类型，将当前时间存入
                    leave.setApplytime(java.sql.Timestamp.valueOf(now));
                    leaveService.addLeave(leave);
                    req.setAttribute("operation", "success");
                    view = STU_ACTION_LIST;
                    break;
                case "edit":
                    // 当前时间
                    now = LocalDateTime.now();
                    leave = new Leave();
                    leave.setLeaveID(req.getParameter("leaveID"));
                    leave.setOpinion(req.getParameter("opinion"));
                    leave.setStatus(req.getParameter("status"));
                    //转类型，将当前时间存入
                    leave.setAudittime(java.sql.Timestamp.valueOf(now));
                    leaveService.editLeave(leave);
                    req.setAttribute("operation", "success");
                    view = INST_ACTION_LIST;
                    break;
                case "export":
                    List<Leave> leaveList = leaveService.list(null);
                    view = VIEW_EXPORT;
                    req.setAttribute("list", leaveList);
                    req.getSession().setAttribute("exportList", leaveList);
                    break;
                case "exportList":
                    System.out.println("执行到这里");
                    // 1.创建工作簿
                    Workbook workbook = new XSSFWorkbook();
                    Sheet sheet = workbook.createSheet("导出数据");
                    // 2.设置表头
                    Row headerRow = sheet.createRow(0);
                    String[] headers = {"请假编号", "课程编号", "请假事由", "天数", "学号", "请假时间", "状态", "审核时间", "审核意见"};
                    for (int i = 0; i < headers.length; i++) {
                        Cell cell = headerRow.createCell(i);
                        cell.setCellValue(headers[i]);
                    }
                    // 3.填充数据
                    leaveList = (List<Leave>) req.getSession().getAttribute("exportList");
                    if (leaveList != null) {
                        int rowNum = 1;
                        for (Leave leave1 : leaveList) {
                            Row row = sheet.createRow(rowNum++);

                            // 填充每一列数据
                            row.createCell(0).setCellValue(leave1.getLeaveID() != null ? leave1.getLeaveID() : "");
                            row.createCell(1).setCellValue(leave1.getCourseID() != null ? leave1.getCourseID() : "");
                            row.createCell(2).setCellValue(leave1.getReason() != null ? leave1.getReason() : "");
                            row.createCell(3).setCellValue(leave1.getDaynum() != null ? leave1.getDaynum() : 0);
                            row.createCell(4).setCellValue(leave1.getStuNo() != null ? leave1.getStuNo() : "");
                            row.createCell(5).setCellValue(leave1.getApplytime() != null ? leave1.getApplytime().toString() : "");
                            row.createCell(6).setCellValue(leave1.getStatus()!= null ? leave1.getStatus() : "");
                            row.createCell(7).setCellValue(leave1.getAudittime() != null ? leave1.getAudittime().toString() : "");
                            row.createCell(8).setCellValue(leave1.getOpinion() != null ? leave1.getOpinion() : "");
                        }
                    } else {
                        System.out.println("没有数据可以导出！");
                    }

                    // 4.设置响应头并返回文件
                    resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                    resp.setHeader("Content-Disposition", "attachment; filename=leave_data.xlsx");
                    try (ServletOutputStream outputStream = resp.getOutputStream()) {
                        workbook.write(outputStream);
                        outputStream.flush();
                    } finally {
                        workbook.close();
                    }
                    break;
                //搜索
                case "search":
                    String keywords = req.getParameter("keywords");
                    leave = new Leave();
                    leave.setCourseID(keywords);
                    List<Leave> list = leaveService.list(leave);
                    view = VIEW_EXPORT;
                    req.setAttribute("list", list);
                    req.getSession().setAttribute("exportList", list);
                    break;
                //删除操作
                case "delete":
                    leaveID = req.getParameter("leaveID");
                    leaveService.deleteLeave(leaveID);
                    req.setAttribute("operation", "success");
                    view = STU_ACTION_LIST;
                    break;
                case "list":
                    String userid = (String) req.getSession().getAttribute("userID");
                    leave = new Leave();
                        leave.setStuNo(userid);
                    leaveList = leaveService.list(leave);
                    view = STU_VIEW_LIST;
                    req.setAttribute("list", leaveList);
                    break;
                case "listAll":
                    leaveList = leaveService.list(null);
                    view = INST_VIEW_LIST;
                    req.setAttribute("list", leaveList);
                    break;
                default:
            }
        }catch (Exception e){
            e.printStackTrace();
            req.setAttribute("message", e.getMessage());
            req.setAttribute("operation", "failure");
            view = STU_ACTION_LIST;
        }
        super.doDispatch(req,resp,view);
    }

    @Override
    public void init() throws ServletException {
        super.init();
        leaveService = AppContext.getBean(LeaveService.class);
        courseService = AppContext.getBean(CourseService.class);
    }
}
